package com.tanhua.mongo.api;

import com.tanhua.dubbo.api.UserLocationApi;
import com.tanhua.model.mongo.UserLocation;
import com.tanhua.model.mongodto.UserLocationDto;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Metric;
import org.springframework.data.geo.Metrics;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;
import java.util.stream.Collectors;

@DubboService
public class UserLocationApiImpl implements UserLocationApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 保存或修改用户地理位置信息
     *
     * @param dto
     * @param userId
     */
    @Override
    public Boolean saveOrUpdate(UserLocationDto dto, Long userId) {
        try {
            UserLocation userLocation = mongoTemplate.findOne(Query.query(Criteria.where("userId").is(userId)), UserLocation.class);
            if (userLocation == null){
                //如果没有数据则添加用户地理位置
                UserLocation u = new UserLocation();
                u.setUserId(userId);
                u.setLocation(new GeoJsonPoint(Double.valueOf(dto.getLongitude().toString()),Double.valueOf(dto.getLatitude().toString())));
                u.setAddress(dto.getAddrStr());
                u.setCreated(System.currentTimeMillis());
                u.setUpdated(System.currentTimeMillis());
                u.setLastUpdated(System.currentTimeMillis());
                mongoTemplate.save(u);
            }else {
                //有该用户数据则修改地理位置
                Update update = Update.update("location",new GeoJsonPoint(Double.valueOf(dto.getLongitude().toString()),Double.valueOf(dto.getLatitude().toString())))
                        .set("updated",System.currentTimeMillis())
                        .set("lastUpdated",userLocation.getUpdated());
                mongoTemplate.updateFirst(Query.query(Criteria.where("userId").is(userId)),update,UserLocation.class);
            }
            return true;
        } catch (NumberFormatException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 搜索附近的人
     *
     * @param userId
     * @param distance
     * @return
     */
    @Override
    public List<Long> findSearchUser(Long userId, String distance) {
        Query query = Query.query(Criteria.where("userId").is(userId));
        UserLocation userLocation = mongoTemplate.findOne(query, UserLocation.class);
        if (userLocation == null){
            return null;
        }
        //2、已当前用户位置绘制原点
        GeoJsonPoint point = userLocation.getLocation();
        //3、绘制半径
        Distance dis = new Distance(Double.valueOf(distance)/1000, Metrics.KILOMETERS);
        //4.绘制圆
        Circle circle = new Circle(point,dis);
        //5.查询
        Query locationQuery = Query.query(Criteria.where("location").withinSphere(circle));
        List<UserLocation> userLocations = mongoTemplate.find(locationQuery, UserLocation.class);

        return userLocations.stream().map(item -> item.getUserId()).collect(Collectors.toList());
    }
}
